package com.xiyoufang.mycli.db;

import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.statement.SQLSelectStatement;
import com.alibaba.druid.sql.parser.ParserException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import picocli.CommandLine;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by 席有芳 on 2021/11/24.
 *
 * @author 席有芳
 */
@CommandLine.Command(name = "execute", description = "数据库工具: 执行脚本")
public class Execute extends Connected {

    /**
     * 数据库名称
     */
    @CommandLine.Option(names = {"-s", "--script"}, description = "脚本, 例如: select 1", interactive = true, echo = true)
    protected String script = "";

    @Override
    protected Integer doCall() {
        if (StrKit.notBlank(script)) {
            try {
                List<SQLStatement> statements = SQLUtils.parseStatements(script, dbType);
                SQLStatement sqlStatement = statements.get(0);
                if (sqlStatement instanceof SQLSelectStatement) {
                    List<Record> records = Db.use().find(script);
                    System.out.println("<" + script + ">脚本已经被执行, 数据: <" + records.size() + ">条");
                    System.out.println(JSON.toJSONStringWithDateFormat(records.stream().map(Record::getColumns).collect(Collectors.toList()), "yyyy-MM-dd HH:mm:ss", SerializerFeature.PrettyFormat));
                } else {
                    int i = Db.use().update(script);
                    System.out.println("<" + script + ">脚本已经被执行, 数据: <" + i + ">条");
                }
            } catch (ParserException e) {
                System.err.println("<" + script + ">解析错误, 请检查脚本是否正确");
            }
        }
        return 0;
    }
}
